<template>
  <div id="g-app">
    <div v-if="books.length">
      <BookList
        :books="books"
        @increment="increment"
        @decrement="decrement"
        @remove="remove"
      />
      <h2>总价格：{{ totalPrice }}</h2>
    </div>
    <h2 v-else>购物车为空</h2>
  </div>
</template>

<script lang="ts" setup>
import {
  computed,
  reactive,
  provide,
  onBeforeMount,
  onBeforeUnmount,
  onBeforeUpdate,
  onMounted,
  onUnmounted,
  onUpdated,
} from "vue";

import BookList from "../components/BookList.vue";

const bookList = reactive([
  {
    id: 1,
    name: "《算法导论》",
    date: "2006-9",
    price: 85.0,
    count: 1,
  },
  {
    id: 2,
    name: "《UNIX编程艺术》",
    date: "2006-2",
    price: 59.0,
    count: 1,
  },
  {
    id: 3,
    name: "《编程珠玑》",
    date: "2008-10",
    price: 39.0,
    count: 1,
  },
  {
    id: 4,
    name: "《代码大全》",
    date: "2006-3",
    price: 128.0,
    count: 1,
  },
]);

const books = bookList;

const increment = (index: number) => {
  books[index].count++;
  console.log("Increment called in:", new Error().stack); // 打印调用栈
};

const decrement = (index: number) => {
  if (books[index].count > 1) {
    books[index].count--;
  }
};

const remove = (index: number) => {
  books.splice(index, 1);
};

const totalPrice = computed(() => {
  return books.reduce((total, book) => {
    return total + book.price * book.count;
  }, 0);
});
// 优化props的逐级透传问题
// Provide methods to child components
provide("increment", increment);
provide("decrement", decrement);
provide("remove", remove);

/* 组件的生命周期 */
onBeforeMount(() => {
  console.log("祖组件的onBeforeMount --- 祖组件挂载前");
});
onMounted(() => {
  console.log("祖组件的onMounted --- 祖组件挂载");
});
onBeforeUnmount(() => {
  console.log("祖组件onBeforeUnmount  --- 祖组件卸载前");
});
onUnmounted(() => {
  console.log("祖组件的onUnmounted  --- 祖组件卸载");
});
onBeforeUpdate(() => {
  console.log("祖组件的onBeforeUpdate --- 祖组件数据更新前");
});
onUpdated(() => {
  console.log("祖组件的onUpdate --- 祖组件数据更新");
});
</script>
